<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller\Admin\Sys;

use App\Controller\AbstractController;
use App\Middleware\AuthMiddleware;
use App\Model\OperateLog;
use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\DeleteMapping;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\Middlewares;

#[Middlewares([AuthMiddleware::class])]
#[Controller]
class OperateLogController extends AbstractController
{
    #[GetMapping(path: '/sys/operateLog')]
    public function list()
    {
        $username = $this->request->input('username', '');
        $operation = $this->request->input('operation', '');
        $startTime = $this->request->input('startTime', '');
        $endTime = $this->request->input('endTime', '');
        $pageNum = $this->request->input('pageNum', 1);
        $pageSize = $this->request->input('pageSize', 10);
        $where = [];
        if ($operation){
            $where[] = ['operation_name', 'like', '%' . $operation . '%'];
        }
        if ($username){
            $where[] = ['username', 'like', '%' . $username . '%'];
        }
        if ($startTime && $endTime){
            $where[] = ['create_time', '>=', $startTime];
            $where[] = ['create_time', '<=', $endTime];
        }

        $list = OperateLog::query()->where($where)->forPage($pageNum, $pageSize)->get();
        $data['searchCount'] = true;
        $data['current'] = (int) $pageNum;
        $data['size'] = (int) $pageSize;
        $data['total'] = OperateLog::query()->count();
        $data['pages'] = ceil($data['total'] / $pageSize);
        $data['records'] = $list;
        return success($data);
    }

    #[DeleteMapping(path: '/sys/operateLog/delete/{ids}')]
    public function delete($ids)
    {
        try {
            $idArr = explode(',', $ids);
            OperateLog::query()->where('id', $idArr)->delete();
            return success();
        } catch (\Throwable $e) {
            Db::rollBack();
            logInfo('delete', $e->getMessage(), 'operateLog');
        }

    }
}
